<?php

namespace app\task\cron;

use yunwuxin\cron\Task;
use think\facade\Db;

/**
 * 代理商余额快照.【每天 23:59 生成】
 */
class AgentBalanceSnapshot extends Task
{
    public function configure()
    {
        // 分 时 日 月 周
        $this->expression = '59 23 * * *';
    }

    public function handle()
    {
        echo '代理商余额快照开始--' . date('Y-m-d H:i:s') . PHP_EOL;
        $lockKey = 'agent_balance_snapshot_lock_key';
        $lockVal = cache($lockKey);
        if ($lockVal) {
            echo '还在处理呢' . PHP_EOL;

            return true;
        }

        cache($lockKey, 1, 120);

        $today = date('Y-m-d');
        $exists = Db::name('agent_daily_balance')
            ->where('dateymd', $today)
            ->value('id');
        if ($exists) {
            echo '执行过了...' . PHP_EOL;
            return true;
        }

        $list = Db::name('agent')
            ->field('id as agent_id, balance, profit_balance, withdraw_amount, recharge_amount,
            total_profit, balance_last_updated_at')
            ->select()
            ->toArray();
        foreach ($list as $k => $v) {
            $list[$k]['dateymd'] = $today;
        }
        Db::name('agent_daily_balance')
            ->insertAll($list);

        cache($lockKey, null);

        echo '代理商余额快照结束--' . date('Y-m-d H:i:s') . PHP_EOL;
    }
}
